package edu.nf.supermarket.web.controller.app;

import edu.nf.supermarket.base.BaseController;
import edu.nf.supermarket.config.FilePathConfig;
import edu.nf.supermarket.entity.Coupon;
import edu.nf.supermarket.entity.Orders;
import edu.nf.supermarket.entity.User;
import edu.nf.supermarket.result.ResultVO;
import edu.nf.supermarket.service.CouponService;
import edu.nf.supermarket.service.OrderService;
import edu.nf.supermarket.service.UserService;
import edu.nf.supermarket.util.OrderNOGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * @author yjj
 * @date 2025-05-20
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private FilePathConfig filePathConfig;

    /**
     * 用户登录方法
     *
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ResultVO<String> login(@RequestParam("phone") String phone
            , @RequestParam("password") String password) {

        String token = userService.login(phone, password);
        return success(token);
    }

    /**
     * 注册新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResultVO<String> register(@RequestBody User user) {
        System.out.println(user.toString());
        user.setAvatar("D:\\Java\\supermarketPrudect\\static\\supermarket-static\\photo\\Profile picture\\logo.png");
        userService.addUser(user);

        //在新用户注册时赠送两张优惠卷
//        couponService.addCoupon(4, user.getUserId(), (byte) 0);
//        couponService.addCoupon(2, user.getUserId(), (byte) 0);

        //在新用户注册时，创建一个订单，作为购物车使用，默认为空
        Orders orders = new Orders();
        orders.setOrderId(OrderNOGenerator.generateOrderNO());
        orders.setOrderStatus((byte) 1);
        orderService.addOrder(user.getUserId(), orders, null, null);
        return success();
    }

    /**
     * 用户上传头像
     *
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/addAvatar")
    public ResultVO<String> addAvatar(@RequestParam("file") MultipartFile file,
                                      @RequestParam("userId") Integer userId) throws IOException {
        if(!isValidFileType(file.getContentType())){
            return fail(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "文件格式错误");
        }


        // 使用配置的路径
        String uploadDir = filePathConfig.getAvatarPath();

        // 处理跨平台路径
        Path uploadPath = Paths.get(uploadDir).normalize();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "." + getFileExtension(file.getOriginalFilename());
        Path filePath = uploadPath.resolve(fileName);

        try {
            file.transferTo(filePath.toFile());

            // 存储相对路径（关键！）
            String relativePath = "/static/photo/avatars/" + fileName;
            userService.addAvatar(userId, relativePath);

            return success(relativePath);
        } catch (IOException e) {
            e.printStackTrace();
            return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "头像上传失败");
        }
    }
    // 获取文件扩展名
    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 校验文件类型
     * @return
     */
    public boolean isValidFileType(String fileType) {
        String[] validFileTypes = {"image/jpeg", "image/png", "image/jpg","image/webp"};
        for (String type : validFileTypes) {
            if (type.equals(fileType)) {
                return true;
            }
        }
        return false;
    }

    @GetMapping("/test")
    public String test() {
        return "OK";
    }

    @PostMapping("/findUserById")
    public ResultVO<User> findUserById(@RequestParam("userId") Integer userId) {
        User user = userService.findUserBuId(userId);
        return success(user);
    }
    /**
     * 获取用户的优惠卷列表
     */
    @GetMapping("/findCouponByUserId")
    public ResultVO<List<Coupon>> findCouponByUserId(@RequestParam("userId") Integer userId) {
        List<Coupon> couponByUserId = couponService.findCouponByUserId(userId);
        return success(couponByUserId);
    }

    /**
     * 检查用户是否是新用户
     * @param userId
     * @return
     */
    @GetMapping("/checkNewUser")
    public ResultVO<Boolean> checkNewUser(@RequestParam("userId") Integer userId){
        boolean isNew = userService.isNewUserForCouponCheck(userId);
        return success(isNew);
    }
}

